/**
 * Created by midori on 2015/12/8.
 */
(function (){
    var PromiseWrapper, module;

    module = angular.module("services.PromiseWrapper",[]);

    PromiseWrapper = (function() {
        PromiseWrapper.make = function(promise) {
            return new PromiseWrapper(promise);
        };

        function PromiseWrapper(promise, name) {
            this.promise = promise;
            this.name = name;
            this.isResolved = false;
            this.isError = false;
            this.error = {};
            this.value = void 0;
            this.callback = void 0;
            this.augmentedPromise = this.promise.then((function(_this) {
                return function(resultSuccess) {
                    _this.isResolved = true;
                    _this.value = resultSuccess;
                    if (_this.callback != null) {
                        _this.callback(_this);
                    }
                    return resultSuccess;
                };
            })(this), (function(_this) {
                return function(resultFailure) {
                    _this.isResolved = true;
                    _this.isError = true;
                    if (_this.callback != null) {
                        _this.callback(_this);
                    }
                    if (resultFailure.status === 0) {
                        _this.error.isTimeout = true;
                    } else {
                        _this.error.isTimeout = false;
                        _this.error.status = resultFailure.status;
                        _this.error.code = resultFailure.data.code;
                        _this.error.message = resultFailure.data.message;
                    }
                    return resultSuccess;
                };
            })(this));
        }

        PromiseWrapper.prototype.onChange = function(callback) {
            return this.callback = callback;
        };

        PromiseWrapper.prototype.then = function(onSuccess, onFailure) {
            return PromiseWrapper.make(this.augmentedPromise.then(onSuccess, onFailure));
        };

        return PromiseWrapper;

    })();

    module.factory("PromiseWrapper", function() {
        return {
            make: function(promise, name) {
                if (name == null) {
                    name = "anonymous";
                }
                return new PromiseWrapper(promise, name);
            }
        };
    });

})(this);
